package com.yanchangapp.ui.activity.purchase.record;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.luck.picture.lib.decoration.RecycleViewDivider;
import com.luck.picture.lib.tools.ScreenUtils;
import com.yanchangapp.R;
import com.yanchangapp.adapter.GRecordCommentAdapter;
import com.yanchangapp.adapter.part.ProductEditNumAdapter;
import com.yanchangapp.commom.LoadingType;
import com.yanchangapp.model.bean.RecordCommentBean;
import com.yanchangapp.model.bean.RecordProductBean;
import com.yanchangapp.model.response.RecordDetailResponse;
import com.yanchangapp.ui.presenter.RecordRejectAtPresenter;
import com.yanchangapp.ui.view.RecordRejectAtView;
import com.yanchangapp.widget.SupplierListBottomDelegate;
import com.yanchangapp.widget.SupplierNumDialog;
import com.zxl.baselib.ui.base.BaseActivity;
import com.zxl.baselib.util.ui.ResHelper;
import com.zxl.baselib.util.ui.UIUtils;
import com.zxl.baselib.widget.NiceNestedScrollView;
import com.zxl.baselib.widget.YCLoadingView;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;

import static com.yanchangapp.ui.activity.purchase.record.GoodsRecordActivity.REFRESH_RECORD_LIST;
public class RecordRejectActivity extends BaseActivity<RecordRejectAtView, RecordRejectAtPresenter> implements RecordRejectAtView, ProductEditNumAdapter.RecordProductListener {
    @BindView(R.id.ivToolbarNavigation)
    ImageView ivToolbarNavigation;
    @BindView(R.id.vToolbarDivision)
    View vToolbarDivision;
    @BindView(R.id.tvToolbarTitle)
    TextView tvToolbarTitle;
    @BindView(R.id.tvDel)
    TextView tvDel;
    @BindView(R.id.tvEnsure)
    TextView tvEnsure;
    @BindView(R.id.llEditState)
    LinearLayout llEditState;
    @BindView(R.id.tvEnsureSubmit)
    TextView tvEnsureSubmit;
    @BindView(R.id.bottom)
    RelativeLayout bottom;
    @BindView(R.id.tvTag)
    TextView tvTag;
    @BindView(R.id.tvBuyerNameTitle)
    TextView tvBuyerNameTitle;
    @BindView(R.id.tvBuyerName)
    TextView tvBuyerName;
    @BindView(R.id.tvTimeTitle)
    TextView tvTimeTitle;
    @BindView(R.id.tvTime)
    TextView tvTime;
    @BindView(R.id.rvOrderDetail)
    RecyclerView rvOrderDetail;
    @BindView(R.id.llApproveTitle)
    LinearLayout llApproveTitle;
    @BindView(R.id.rvApprove)
    RecyclerView rvApprove;
    @BindView(R.id.ivImage)
    ImageView ivImage;
    @BindView(R.id.rlApproveEmpty)
    RelativeLayout rlApproveEmpty;
    @BindView(R.id.scrollView)
    NiceNestedScrollView scrollView;
    @BindView(R.id.btnNextRefresh)
    TextView btnNextRefresh;
    @BindView(R.id.llErrorNetwork)
    LinearLayout llErrorNetwork;
    @BindView(R.id.ycLoading)
    YCLoadingView ycLoading;
    private int mID;
    private static final String ID = "id";
    private List<RecordProductBean> mRecordProductBeans = new ArrayList<>();
    private ProductEditNumAdapter mProductEditNumAdapter;
    private List<RecordCommentBean> mRecordCommentBeans = new ArrayList<>();
    private GRecordCommentAdapter mGRecordCommentAdapter;
    // 选中的供货商ID以及供货商姓名...
    private String selectSupplierId, selectSupplierName,tips,currentNum;
    private int selectNum;
    private int currentIndex;
    private int mInnerRecommend;
    private int mInnerSmall;
    private SupplierNumDialog mSupplierNumDialog;
    private SupplierListBottomDelegate.Builder mSupplierBuilder;

    public static void show(Activity activity, int id) {
        Intent intent = new Intent(activity, RecordRejectActivity.class);
        intent.putExtra(ID, id);
        activity.startActivity(intent);
    }

    @Override
    protected void init() {
        if (getIntent() != null && getIntent().hasExtra(ID)) {
            mID = getIntent().getIntExtra(ID, -1);
        } else {
            finish();
        }
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_record_reject;
    }

    @Override
    protected RecordRejectAtPresenter createPresenter() {
        return new RecordRejectAtPresenter(this);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tvToolbarTitle.setText("记录详情");
        initAdapter();
    }

    private void initAdapter() {
        // 设置商品的Adapter
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        manager.setSmoothScrollbarEnabled(true);
        manager.setAutoMeasureEnabled(true);
        rvOrderDetail.setHasFixedSize(true);
        rvOrderDetail.setNestedScrollingEnabled(false);
        rvOrderDetail.setLayoutManager(manager);
        mProductEditNumAdapter = new ProductEditNumAdapter(this, mRecordProductBeans, this);
        mProductEditNumAdapter.setNumShow(false);
        rvOrderDetail.setAdapter(mProductEditNumAdapter);

        // 设置评论的Adapter
        LinearLayoutManager managerComment = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        managerComment.setSmoothScrollbarEnabled(true);
        managerComment.setAutoMeasureEnabled(true);
        rvApprove.setHasFixedSize(true);
        rvApprove.setNestedScrollingEnabled(false);
        rvApprove.setLayoutManager(managerComment);
        rvApprove.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, ScreenUtils.dip2px(this, 0.5f), ContextCompat.getColor(this, R.color.borderColorBase)));
        mGRecordCommentAdapter = new GRecordCommentAdapter(R.layout.item_comment_record_approve, mRecordCommentBeans);
        rvApprove.setAdapter(mGRecordCommentAdapter);
    }

    @Override
    protected void initData() {
        setLoadingState(LoadingType.LOADING);
        mPresenter.queryRecordDetail(mID);
    }

    @Override
    protected void initListener() {
        ivToolbarNavigation.setOnClickListener(v -> finish());

        tvEnsure.setOnClickListener(v -> {
            mProductEditNumAdapter.setEditType();
            llEditState.setVisibility(View.GONE);
            tvEnsureSubmit.setVisibility(View.VISIBLE);
        });

        tvEnsureSubmit.setOnClickListener(v -> mPresenter.submitToApprove(mID));

        tvDel.setOnClickListener(v -> mPresenter.deleteApprove(mID));
    }


    private void recallBackData(int innerNum) {
        selectNum = innerNum;
        mPresenter.submitRecord(mRecordProductBeans.get(currentIndex).getId(),
                selectSupplierId, innerNum);
    }

    private void showSupplierNum(){
        mSupplierNumDialog = new SupplierNumDialog.Builder(this)
                .setBuyNum(currentNum)
                .setBuyRange(mInnerSmall,mInnerRecommend)
                .setSupplierName(selectSupplierName)
                .setTipsString(tips)
                .setEnsureListener(this::recallBackData)
                .setJumpSupplierListener(numStr -> {
                    currentNum = numStr;
                    showSupplierBottom();
                })
                .build();
        mSupplierNumDialog.show();
    }

    private void showSupplierBottom(){
        if (mSupplierBuilder == null){
            mSupplierBuilder = new SupplierListBottomDelegate.Builder(this)
                    .setDismissListener(this::showSupplierNum)
                    .setEnsureListener((supplierID, supplierName) -> {
                        selectSupplierId = supplierID;
                        selectSupplierName = supplierName;
                    })
                    .create();
        }
        mSupplierBuilder.setData(mRecordProductBeans.get(currentIndex).getSuppliers())
                .setSelectSupplier(selectSupplierId)
                .show();
    }


    private void setLoadingState(LoadingType loadingType) {
        switch (loadingType) {
            case LOADING:
                if (ycLoading.getVisibility() == View.GONE) {
                    ycLoading.setVisibility(View.VISIBLE);
                }

                if (scrollView.getVisibility() == View.VISIBLE) {
                    scrollView.setVisibility(View.GONE);
                    bottom.setVisibility(View.GONE);
                }

                if (llErrorNetwork.getVisibility() == View.VISIBLE) {
                    llErrorNetwork.setVisibility(View.GONE);
                }
                break;
            case SUCCESS:

                if (ycLoading.getVisibility() == View.VISIBLE) {
                    ycLoading.setVisibility(View.GONE);
                }

                if (scrollView.getVisibility() == View.GONE) {
                    scrollView.setVisibility(View.VISIBLE);
                    bottom.setVisibility(View.VISIBLE);
                }


                if (llErrorNetwork.getVisibility() == View.VISIBLE) {
                    llErrorNetwork.setVisibility(View.GONE);
                }
                break;
            case ERROR:
                if (ycLoading.getVisibility() == View.VISIBLE) {
                    ycLoading.setVisibility(View.GONE);
                }

                if (scrollView.getVisibility() == View.VISIBLE) {
                    scrollView.setVisibility(View.GONE);
                    bottom.setVisibility(View.GONE);
                }


                if (llErrorNetwork.getVisibility() == View.GONE) {
                    llErrorNetwork.setVisibility(View.VISIBLE);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void queryDetailSuccess(RecordDetailResponse response) {
        setLoadingState(LoadingType.SUCCESS);
        // 设置对应的标签信息...
        tvTag.setText(response.getExamineStatusName());
        tvTag.setBackground(ResHelper.getDrawable(R.drawable.tag_order_reject));
        if (response.getAuditLogs().size() != 0) {
            rlApproveEmpty.setVisibility(View.GONE);
        }
        tvBuyerName.setText(getString(R.string.order_detail_name_dept, response.getBuyer(), response.getDepartment()));
        // 设置创建时间...
        tvTime.setText(response.getCreateTime());
        // 刷新商品列表的数据
        mRecordProductBeans.addAll(response.getRecords());
        mProductEditNumAdapter.notifyDataSetChanged();
        // 刷新评论列表数据
        mRecordCommentBeans.addAll(response.getAuditLogs());
        mGRecordCommentAdapter.notifyDataSetChanged();
    }

    @Override
    public void queryDetailFailure(String err) {
        setLoadingState(LoadingType.ERROR);
        UIUtils.showToast(err);
    }

    @Override
    public void editRecordSuccess() {
        RecordProductBean bean = mRecordProductBeans.get(currentIndex);
        bean.setPurchaseNum(selectNum);
        bean.setSupplierId(selectSupplierId);
        bean.setSupplierName(selectSupplierName);
        mProductEditNumAdapter.notifyItemChanged(currentIndex, ProductEditNumAdapter.JUST_REFRESH_NUM_SUPPLIER);
        // 进行隐藏
        mSupplierNumDialog.dismiss();
        UIUtils.showToast("修改成功");
    }

    @Override
    public void editRecordFailure(String err) {
        UIUtils.showToast(err);
    }

    @Override
    public void submitToApproveSuccess() {
        //
        // 页面退出并提示刷新
        UIUtils.showToast("提交审批成功");
        mRxManager.post(REFRESH_RECORD_LIST, true);
        finish();
    }

    @Override
    public void submitToApproveFailure(String err) {
        UIUtils.showToast(err);
    }

    @Override
    public void deleteSuccess() {
        UIUtils.showToast("删除成功");
        mRxManager.post(REFRESH_RECORD_LIST, true);
        finish();
    }

    @Override
    public void deleteFailure(String err) {
        UIUtils.showToast(err);
    }

    @Override
    public void onProductNumClick(int position) {
        currentIndex = position;
        // 设置数据并进行显示
        RecordProductBean bean = mRecordProductBeans.get(currentIndex);
        selectSupplierId = String.valueOf(bean.getSupplierId());
        selectSupplierName = bean.getSupplierName();
        mInnerRecommend = bean.getAlarmMax() - bean.getInventoryNumber();
        mInnerSmall = bean.getAlarmMin() - bean.getInventoryNumber();
        if (mInnerSmall < 0){
            mInnerSmall = 0;
        }
        if (mInnerRecommend == 0) {
            tips = "库存无法存放";
        } else {
            tips = getString(R.string.apply_tips, mInnerSmall, mInnerRecommend);
        }
        currentNum = String.valueOf(bean.getPurchaseNum());
        showSupplierNum();
    }
}
